package service

import (
	"context"
	"gitee.com/perception-network/block-chain-released/internal/model"
	"gitee.com/perception-network/block-chain-released/internal/repository"
	"gitee.com/perception-network/block-chain-released/pkg/blockChain"
	_ "gitee.com/perception-network/block-chain-released/pkg/blockChain/register"
	"go.uber.org/zap"
)

type BlockChainReleaser interface {
	GetBlockChainReleaseData(ctx context.Context) ([]*model.Release, error)
	RunBlockChainReleaseCheck(ctx context.Context)
}

var _ BlockChainReleaser = (*blockChainReleaseServiceImpl)(nil)

type blockChainReleaseServiceImpl struct {
	bc   chan blockChain.BlockChainMsg
	repo repository.BlockChain
}

func NewBlockChainReleaseServiceImpl(repo repository.BlockChain) *blockChainReleaseServiceImpl {
	return &blockChainReleaseServiceImpl{
		bc:   make(chan blockChain.BlockChainMsg),
		repo: repo,
	}
}

func (b *blockChainReleaseServiceImpl) GetBlockChainReleaseData(ctx context.Context) ([]*model.Release, error) {
	return b.repo.GetData(ctx)
}

func (b *blockChainReleaseServiceImpl) RunBlockChainReleaseCheck(ctx context.Context) {
	blockChain.BlockChainMapRun(b.bc)
	go func() {
		for bc := range b.bc {
			err := b.repo.AddOne(ctx, &model.Release{
				Name:    bc.Name,
				Version: bc.Version,
			})
			if err != nil {
				log.Error("failed to add release", zap.Any("data", bc), zap.Error(err))
			}
		}
	}()
}
